package com.zHan.sky.service.impl;

import com.zHan.sky.dto.GoodsSalesDTO;
import com.zHan.sky.entity.Orders;
import com.zHan.sky.mapper.OrderDetailMapper;
import com.zHan.sky.mapper.OrdersMapper;
import com.zHan.sky.service.OrdersService;
import com.zHan.sky.service.ReportService;
import com.zHan.sky.service.UserService;
import com.zHan.sky.service.WorkSpaceService;
import com.zHan.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: ReportServiceImpl
 * Description:
 * date: 2023/8/1 0001 15:39
 *
 * @author zHan
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkSpaceService workSpaceService;

    /**
     * 获得时间区间内的营业额数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDateList(begin, end);
        // 存放总营业额
        List<Double> turnoverList = new ArrayList<>();
        // 遍历时间集合
        dateList.stream().forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer status = Orders.COMPLETED;
            // 获取每天的营业额
            Double turnover = ordersMapper.selectTotalAmount(beginTime, endTime, status);
            turnover = turnover == null ? 0 : turnover;
            // 新增营业额集合
            turnoverList.add(turnover);
        });

        // 返回数据
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDateList(begin, end);
        // 存放每天的总用户数量
        List<Integer> totalUserList = new ArrayList<>();
        // 存放每天的新增用户数量
        List<Integer> newUserList = new ArrayList<>();
        // 循环遍历
        dateList.stream().forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 查询总用户数量
            Integer totalUser = userService.getUserCount(beginTime, null);
            // 查询新增用户数量
            Integer newUser = userService.getUserCount(beginTime, endTime);

            // 添加到集合中
            totalUserList.add(totalUser);
            newUserList.add(newUser);
        });
        // 返回数据
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDateList(begin, end);
        // 存放每日订单数
        List<Integer> orderCountList = new ArrayList<>();
        // 存放每日有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();
        // 循环遍历
        dateList.stream().forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 查询每日订单数
            Integer orderCount = ordersService.getOrderCount(beginTime, endTime, null);
            orderCountList.add(orderCount);

            // 查询每日有效订单数
            Integer validOrderCount = ordersService.getOrderCount(beginTime, endTime,
                    Orders.COMPLETED);
            validOrderCountList.add(validOrderCount);
        });

        // 查询订单总数，不需要查询数据库版！
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        // 查询有效订单数，不需要查询数据库版！
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        // 订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        // 返回数据
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询销量排名top10
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        // 查询每日销量名称
        List<GoodsSalesDTO> goodsSalesDTOList = orderDetailMapper.selectSalesTop10(beginTime,
                endTime);
        // 获取商品名称列表
        List<String> nameList =
                goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        // 获取销量列表
        List<Integer> numberList =
                goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        // 返回数据
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出运营数据
     *
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 查询数据库，获取营业数据 -- 近30天的数据
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(beginDate, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(endDate, LocalTime.MAX);
        // 查询概览数据
        BusinessDataVO businessDataVO = workSpaceService.getBusinessData(beginTime, endTime);
        // 通过POI将数据写入到Excel文件中
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(
                "template/运营数据报表模板.xlsx");
        try {
            // 基于模板文件创建一个excel文件
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            // 获取表格文字的sheet页
            XSSFSheet sheet = excel.getSheetAt(0);
            // 填充时间数据
            sheet.getRow(1).getCell(1).setCellValue("时间：" + beginDate + " 至 " + endDate);
            // 获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            // 获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            // 查询明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = beginDate.plusDays(i);
                LocalDateTime begin = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime end = LocalDateTime.of(date, LocalTime.MAX);
                // 查询某一天的营业数据
                BusinessDataVO businessData = workSpaceService.getBusinessData(begin, end);
                // 获得某一行，从第8行开始
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());

            }
            // 通过输出流将Excel文件下载到浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            // 关闭资源
            outputStream.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 获取时间集合
     *
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getLocalDateList(LocalDate begin, LocalDate end) {
        // 存放时间集合
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        // 循环添加时间集合
        while (!end.equals(begin)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
}
